const myEnv = {
  inH5: false,
  inWx: false,
  inMp: false,
  inMpWx: false,
  inDev: false,
  inIos: uni.$u.os() === "ios",
  inAndroid: uni.$u.os() === "android",
};

// #ifdef H5
myEnv.inH5 = true;
myEnv.inWx = /micromessenger/i.test(navigator.userAgent);
myEnv.inDev = /localhost/.test(location.host);
// #endif

// #ifdef APP
myEnv.inApp = true;
// #endif

// #ifdef MP
myEnv.inMp = true;
// #endif

// #ifdef MP-WEIXIN
myEnv.inMpWx = true;
// #endif

export default {
  ...myEnv,
  sleep(msec) {
    return new Promise((resolve) => {
      setTimeout(resolve, msec);
    });
  },
  showActions(title, acts) {
    // acts: [[txt: fn], ...]
    uni.showActionSheet({
      title,
      itemList: acts.map((arr) => arr[0]),
      success: (e) => {
        const fn = acts[e.tapIndex][1];
        if (fn) fn();
      },
    });
  },
  loading(title = "加载中") {
    uni.showLoading({
      title,
    });
  },
  hideLoading() {
    uni.hideLoading();
  },
  toast(title, icon = "none") {
    if (icon == 1) {
      icon = "success";
    }
    uni.showToast({
      title,
      icon,
    });
  },
  alert(content, opts = {}) {
    return new Promise((resolve) => {
      uni.showModal({
        content,
        showCancel: false,
        ...opts,
        success() {
          resolve();
        },
      });
    });
  },
  confirm(title = "", content, opts) {
    if (!content) content = "";
    else if (typeof content == "object") {
      opts = content;
      if (title.length > 10) {
        content = title;
        title = "";
      } else {
        content = "";
      }
    }
    return new Promise((resolve, reject) => {
      if (opts == "popup") {
        uni.showActionSheet({
          title,
          itemList: [content],
          success: () => {
            resolve();
          },
        });
        return;
      }
      uni.showModal({
        title,
        content,
        ...opts,
        success({ confirm }) {
          if (confirm) resolve();
          else reject();
        },
      });
    });
  },
};
